package com.thread.threadfirst.designMode.singleton;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 单例模式
 * 懒汉模式
 * 缺点：有线程安全问题
 */
public class SingletonLazy {

    //注意：这里不加volatile在高并发的情况下（也只有阿里那样的百万高并发情况下）会发生指令重排问题。
    private static volatile SingletonLazy singletonLazy =null;

    public static ThreadPoolExecutor executor=new ThreadPoolExecutor(3,5,3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5),new ThreadPoolExecutor.DiscardPolicy());

    private SingletonLazy() {}

    //注意：singletonLazy不加volatile在高并发的情况下（也只有阿里那样的百万高并发情况下）会发生指令重排问题，
    //因为在new对象过程中 看汇编码是主要有3条命令来执行的，这3条执行顺序在高并发下是会乱序重排的，所以加volatile会阻止乱序重排。
    public static SingletonLazy getInstance(){
        if (singletonLazy ==null) {
            synchronized (SingletonLazy.class){
                if (singletonLazy ==null) {
                    singletonLazy =new SingletonLazy();
                }
            }
        }
        return singletonLazy;
    }

    public void executor(Runnable runnable){
        executor.execute(runnable);
    }

    public void shutdown(){
        executor.shutdown();
    }

    public static void main(String[] args) {
        for (int i=0;i<4;i++){
            SingletonLazy.getInstance().executor(()->{
                System.out.println(SingletonLazy.getInstance());
            });
        }
    }

}
